package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.OrderStatisticsDTO;
import com.sky.dto.TurnoverItemDTO;
import com.sky.dto.UserStatisticsDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics (LocalDate begin, LocalDate end) throws Exception {
        if (begin.isAfter(end)) {
            throw new DateTimeException(MessageConstant.DATE_ILLEGAL);
        }

        LocalDateTime beginTime = begin.atStartOfDay();
        LocalDateTime endTime = end.atTime(LocalTime.MAX);

        List<TurnoverItemDTO> list = ordersMapper.getByDateAndStatus(beginTime, endTime, Orders.COMPLETED);
        List<LocalDate> dateList = new ArrayList<>();
        List<BigDecimal> turnoverList = new ArrayList<>();
        list.forEach(turnoverItemDTO -> {
            dateList.add(turnoverItemDTO.getOrderDate());
            turnoverList.add(turnoverItemDTO.getTotalTurnover());
        });

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) throws Exception {
        if (begin.isAfter(end)) {
            throw new DateTimeException(MessageConstant.DATE_ILLEGAL);
        }

        LocalDateTime beginTime = begin.atStartOfDay();
        LocalDateTime endTime = end.atTime(LocalTime.MAX);

        // 查询总用户数和新增用户数
        List<UserStatisticsDTO> list = userMapper.getUserStatisticsByDateRange(beginTime, endTime);

        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        int previousTotalUser = userMapper.getTotalByBegin(begin);

        for (UserStatisticsDTO userStatisticsDTO : list) {
            // 每天的统计数据
            LocalDate currentDate = userStatisticsDTO.getDate();
            int newUserCount = userStatisticsDTO.getNewUser();

            // 当前日期的总用户数 = 前一天的总用户数 + 当前日期的新增用户数
            int currentTotalUser = previousTotalUser + newUserCount;

            // 添加当前日期和用户数据到列表
            dateList.add(currentDate);
            totalUserList.add(currentTotalUser);
            newUserList.add(newUserCount);

            // 更新前一天的总用户数
            previousTotalUser = currentTotalUser;
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     * @throws Exception
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) throws Exception {
        if (begin.isAfter(end)) {
            throw new DateTimeException(MessageConstant.DATE_ILLEGAL);
        }

        LocalDateTime beginTime = begin.atStartOfDay();
        LocalDateTime endTime = end.atTime(LocalTime.MAX);

        List<OrderStatisticsDTO> list = ordersMapper.getOrderStatisticsByDateRange(beginTime, endTime);

        // 统计数据
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        int totalOrderCount = ordersMapper.getTotalByBegin(begin);
        int validOrderCount = ordersMapper.getValidByBegin(begin, Orders.COMPLETED);

        // 遍历查询结果，计算每日订单数和有效订单数
        for (OrderStatisticsDTO orderStatisticsDTO : list) {
            LocalDate currentDate = orderStatisticsDTO.getDate();
            int dailyOrderCount = orderStatisticsDTO.getTotalOrderCount();  // 每日订单数
            int dailyValidOrderCount = orderStatisticsDTO.getValidOrderCount();  // 每日有效订单数

            // 累计订单总数和有效订单数
            totalOrderCount += dailyOrderCount;
            validOrderCount += dailyValidOrderCount;

            // 将日期、订单数和有效订单数添加到相应的列表
            dateList.add(currentDate);
            orderCountList.add(dailyOrderCount);
            validOrderCountList.add(dailyValidOrderCount);
        }

        // 计算完单率 = 有效订单数 / 所有订单数 * 100%
        double orderCompletionRate = (totalOrderCount > 0) ? ((double) validOrderCount / totalOrderCount) : 0;

        // 返回统计结果
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * top10统计
     * @param begin
     * @param end
     * @return
     * @throws Exception
     */
    @Override
    public SalesTop10ReportVO getSalesTop10Statistics(LocalDate begin, LocalDate end) throws Exception {
        if (begin.isAfter(end)) {
            throw new DateTimeException(MessageConstant.DATE_ILLEGAL);
        }

        LocalDateTime beginTime = begin.atStartOfDay();
        LocalDateTime endTime = end.atTime(LocalTime.MAX);
        List<GoodsSalesDTO> list = ordersMapper.getSalesTop10(beginTime, endTime);

        List<String> names = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     * @throws Exception
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 查询数据库，获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        // 通过POI将数据写入Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("sheet1");

            // 填充数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            // 获得第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            // 获得第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);

                // 查询某一天的营业数据
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                // 获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(5).setCellValue(businessDataVO.getNewUsers());
            }

            // 通过输出流将Excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
